import type { UserState } from '@/store/modules/user/types';

const TOKEN_KEY = 'token';

const isLogin = () => {
  return !!localStorage.getItem(TOKEN_KEY);
};

const getToken = () => {
  return localStorage.getItem(TOKEN_KEY);
};

const setToken = (token: string) => {
  localStorage.setItem(TOKEN_KEY, token);
};

const clearToken = () => {
  localStorage.removeItem(TOKEN_KEY);
};

// 从token中解析用户信息
const parseToken = (_token: string): UserState | null => {
  try {
    // 这里应该根据实际的token格式来解析
    // 如果是JWT，可以这样解析：
    // const base64Url = token.split('.')[1];
    // const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    // return JSON.parse(window.atob(base64));

    // 这里暂时返回模拟的用户信息
    return {
      name: '王立群',
      avatar: '//lf1-xgcdn-tos.pstatp.com/obj/vcloud/vadmin/start.8e0e4855ee346a46ccff8ff3e24db27b.png',
      email: 'wangliqun@email.com',
      job: 'frontend',
      jobName: '前端艺术家',
      organization: 'Frontend',
      organizationName: '前端',
      location: 'beijing',
      locationName: '北京',
      introduction: '人潇洒，性温存',
      personalWebsite: 'https://www.baidu.com',
      phone: '150****0000',
      registrationDate: '2013-05-10 12:10:00',
      accountId: '15012312300',
      certification: 1,
      role: 'admin' as RoleType
    };
  } catch (error) {
    console.error('Failed to parse token:', error);
    return null;
  }
};

export { isLogin, getToken, setToken, clearToken, parseToken };
